package www.wen.com.common.lib.extension

import androidx.lifecycle.LifecycleOwner
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.listener.OnPageChangeListener

/**
 * @author WEN
 * @Description: Banner 的扩展类
 * @date 2021/7/1 19:26
 */


inline fun Banner<*, *>.onPageScrolled(
        crossinline action: (
                position: Int, positionOffset: Float, positionOffsetPixels: Int
        ) -> Unit
) = addOnPageChangeListener(onPageScrolled = action)


inline fun Banner<*, *>.onPageSelected(
        crossinline action: (
                position: Int
        ) -> Unit
) = addOnPageChangeListener(onPageSelected = action)


inline fun Banner<*, *>.onPageScrollStateChanged(
        crossinline action: (state: Int) -> Unit
) = addOnPageChangeListener(onPageScrollStateChanged = action)


inline fun Banner<*, *>.addOnPageChangeListener(
        crossinline onPageScrolled: (
                position: Int, positionOffset: Float, positionOffsetPixels: Int
        ) -> Unit = { _, _, _ -> },
        crossinline onPageSelected: (
                position: Int
        ) -> Unit = { _ -> },
        crossinline onPageScrollStateChanged: (state: Int) -> Unit = {}
): OnPageChangeListener {

    val onPageChangeListener = object : OnPageChangeListener {
        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            onPageScrolled.invoke(position, positionOffset, positionOffsetPixels)
        }

        override fun onPageSelected(position: Int) {
            onPageSelected.invoke(position)
        }

        override fun onPageScrollStateChanged(state: Int) {
            onPageScrollStateChanged.invoke(state)
        }
    }
    addOnPageChangeListener(onPageChangeListener)
    return onPageChangeListener
}

fun <BA: BannerAdapter<*,*>> Banner<*, *>.configuration(
        owner: LifecycleOwner? = null,
        loopTime: Long = 5000,
        isAutoLoop: Boolean = true,
        position: Int = 0,
        smoothScroll: Boolean = true,
        provideAdapter:()->BA,
        onPageSelectedBA:(position: Int) -> Unit
) {
    setLoopTime(loopTime)
    isAutoLoop(isAutoLoop)
    owner?.also { addBannerLifecycleObserver(it) }
    adapter = provideAdapter.invoke()
    setCurrentItem(position, smoothScroll)
    onPageSelected(onPageSelectedBA)
}

